package spring.boot.jwt.service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import spring.boot.jwt.mapper.TUserMapper;
import spring.boot.jwt.model.TUser;

import java.util.Date;

@Service
public class TUserService extends ServiceImpl<TUserMapper, TUser> {

    public static Long EXPIRE_TIME = 1000L * 60L * 60 * 24 * 7;

    public TUser selectByUsername(String username) {
        QueryWrapper<TUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        return getOne(wrapper);
    }

    public TUser selectById(String userId) {
        return getById(userId);
    }

    public String getToken(TUser user) {
        // 将 user id 保存到 token 里面 以 password 作为 token 的密钥
        return JWT.create()
                .withAudience(String.valueOf(user.getId()))
                .withExpiresAt(getExpireDate())
                .sign(Algorithm.HMAC256(user.getPassword()));
    }

    private Date getExpireDate() {
        long now = System.currentTimeMillis();
        long expire = now + EXPIRE_TIME;
        return new Date(expire);
    }

}
